from typing import Tuple, Dict
from app.config import settings

DEFAULT_UA = settings.FAMES_SPIDER_UA or 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'


def parse_cookie_string(cookie_str: str) -> Dict[str, str]:
    out: Dict[str, str] = {}
    for part in (cookie_str or '').split(';'):
        part = part.strip()
        if not part:
            continue
        if '=' not in part:
            continue
        k, v = part.split('=', 1)
        out[k.strip()] = v.strip()
    return out


async def build_platform_auth(platform: str) -> Tuple[Dict, Dict[str, str]]:
    headers = {
        'User-Agent': DEFAULT_UA,
        'Accept': 'application/json, text/plain, */*',
        'Origin': 'https://www.douyin.com' if platform == 'douyin' else 'https://www.kuaishou.com' if platform == 'kuaishou' else 'https://m.weibo.cn' if platform == 'weibo' else 'https://www.xiaohongshu.com' if platform == 'xhs' else '',
        'Referer': '',
    }
    cookie_dict: Dict[str, str] = {}
    # Env cookie override
    env_cookie = ''
    if platform == 'weibo':
        env_cookie = settings.FAMES_SPIDER_WEIBO_COOKIE or ''
    elif platform == 'douyin':
        env_cookie = settings.FAMES_SPIDER_DOUYIN_COOKIE or ''
    elif platform == 'kuaishou':
        env_cookie = settings.FAMES_SPIDER_KUAISHOU_COOKIE or ''
    elif platform == 'xhs':
        env_cookie = settings.FAMES_SPIDER_XHS_COOKIE or ''
    if env_cookie:
        headers['Cookie'] = env_cookie
        cookie_dict = parse_cookie_string(env_cookie)
        return headers, cookie_dict
    try:
        from .login.playwright import init_browser_context
        context = await init_browser_context()
        if context:
            if platform == 'douyin':
                from .vendor.mindspider.login.douyin import login as plat_login
            elif platform == 'kuaishou':
                from .vendor.mindspider.login.kuaishou import login as plat_login
            elif platform == 'weibo':
                from .vendor.mindspider.login.weibo import login as plat_login
            elif platform == 'xhs':
                from .vendor.mindspider.login.xhs import login as plat_login
            else:
                plat_login = None
            if plat_login:
                cookie_str, cookie_dict = await plat_login(context)
            else:
                cookie_str, cookie_dict = ('', {})
            if cookie_str:
                headers['Cookie'] = cookie_str
    except Exception:
        pass
    return headers, cookie_dict
